//
//  Y2BackendService.m
//  Pods-Y2NetWorking_Example
//
//  Created by ycgame on 2020/11/24.
//

#import "Y2BackendService.h"
#import "Y2Networking.h"
#import "Y2Encrypt.h"
#import "Y2Common.h"

@interface Y2BackendService ()
@property(nonatomic, strong)NSString *suiteName;
@property(nonatomic, strong)Y2HTTPSessionManager *httpManager;
@end

//
static NSMutableDictionary *instances = nil;

@implementation Y2BackendService

+ (instancetype)serviceWithSuiteName:(NSString *)name {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instances = [[NSMutableDictionary alloc] initWithCapacity:2];
    });
    Y2BackendService *service = instances[name];
    if (service == nil) {
        service = [[Y2BackendService alloc] init];
        [instances setValue:service forKey:name];
    }
    return service;
}

- (void)setConfig:(Y2BackendConfiguration *)config {
    Y2ParameterAssert(config);
    _config = config;
    NSURL *baseURL = [NSURL URLWithString:_config.baseURL];
    Y2ParameterAssert(baseURL);
    _httpManager = [[Y2HTTPSessionManager alloc] initWithBaseURL:baseURL];
}

- (void)request:(Y2BackendRequest *)request success:(nullable void (^)(id _Nullable responseObj))success failure:(nullable void (^)(NSError * _Nonnull error))failure {

    Y2ParameterAssert(_httpManager);
    
    // 添加默认headers
    NSMutableDictionary *mutableHeaders = [Y2BackendService defaultHeaders].mutableCopy;
    for (NSString *key in request.headers) {
        [mutableHeaders setValue:request.headers[key] forKey:key];
    }
    request.headers = mutableHeaders.copy;
    
    // 添加默认parameters
    NSMutableDictionary *mutableParameters = [Y2BackendService defaultParameters].mutableCopy;
    for (NSString *key in request.parameters) {
        [mutableParameters setValue:request.parameters[key] forKey:key];
    }
    request.parameters = mutableParameters.copy;
    
    // 生成加密后的参数
    NSDictionary *parameters = [self parametersWithDict:request.parameters];
    
    NSURLSessionDataTask *dataTask = [_httpManager dataTaskWithHTTPMethod:request.method URLString:request.endPoint parameters:parameters headers:request.headers uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) { success(responseObject); }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) { failure(error); }
    }];
    [dataTask resume];
}

//- (void)get:(Y2BackendRequest *)request success:(nullable void (^)(id _Nullable))success failure:(nullable void (^)(NSError * _Nonnull))failure {
//    NSURL *baseURL = [NSURL URLWithString:_config.baseURL];
//    Y2HTTPSessionManager *manager = [[Y2HTTPSessionManager alloc] initWithBaseURL:baseURL];
//    [manager GET:request.endPoint parameters:request.parameters headers:request.headers progress:^(NSProgress * _Nonnull downloadProgress) {
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        if (success) { success(responseObject); }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        if (failure) { failure(error); }
//    }];
//}
//
//- (void)post:(Y2BackendRequest *)request success:(nullable void (^)(id _Nullable))success failure:(nullable void (^)(NSError * _Nonnull))failure {
//    NSURL *baseURL = [NSURL URLWithString:_config.baseURL];
//    Y2HTTPSessionManager *manager = [[Y2HTTPSessionManager alloc] initWithBaseURL:baseURL];
//    [manager POST:request.endPoint parameters:request.parameters headers:request.headers progress:^(NSProgress * _Nonnull uploadProgress) {
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        if (success) { success(responseObject); }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        if (failure) { failure(error); }
//    }];
//}


// 生成参数
- (NSDictionary *)parametersWithDict:(NSDictionary *)dict {
    NSString *v = dict[@"grant_app"] ?: @"";
    NSString *q = [dict rsaWithKey:_config.publicKey] ?: @"";
    return @{@"q": q, @"v": v};
}

+ (NSDictionary *)defaultParameters {
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970] * 1000;
    NSString *timestamp = [NSString stringWithFormat:@"%f", timeInterval];
    return @{
        @"device_id": @"E1C1CEC7-63EF-42B4-BE8D-2DD05AB0D841",
        @"device_type": @"iOS",
        @"grant_app": @"SUPER_ADMIN_APP_ID",
        @"channel": @"test",
        @"bind_id": @"E1C1CEC7-63EF-42B4-BE8D-2DD05AB0D841",
        @"bind_type": @"device",
        @"time": timestamp
    };
}

+ (NSDictionary *)defaultHeaders {
    return @{
        @"Accept-Language": @"zh-CN",
        @"Content-Type": @"application/x-www-form-urlencoded"
    };
}

@end
